﻿// DateSelector shows a date selector dialog when clicked
define([
    'Wjs/ui/widgets/tools/Tool',
    'Wjs/ui/widgets/Tooltip',
    'Wjs/ui/widgets/DatePicker'
],
function () {
    'use strict';

    return Wjs.defineOnce({

        type: 'DateSelector',

        internal: {

            base: Wjs.getType('Tool'),

            initialize: function () {
                var me = this;

                me.addClass('wjs-date-selector');

                me.datePicker = Wjs.new('Tooltip')

                                    .setTarget(me)

                                    .setAction('click')

                                    .setItem(

                                        Wjs.new('DatePicker')

                                            .onDateSelected(function (date) {

                                                if (me.dateSelectedHandler) {

                                                    me.dateSelectedHandler(date);
                                                }
                                            })
                                    );

                me.datePicker.addEvents({

                    mouseleave: function () {

                        if (!me.datePicker.isHidden()) { // The date picker can be already hidden when the day cell is clicked and the mouseleave event still will fire

                            me.datePicker.hide();
                        }
                    }
                });

                me.onRender(function () {

                    me.datePicker.render();
                });

                me.onClick(function (event) {

                    me.datePicker.show();
                });

            }
        },

        getDatePicker: function () {

            return this.datePicker;
        },

        onDateSelected: function (fcn) {

            this.dateSelectedHandler = Wjs.chain(this.dateSelectedHandler, fcn);

            return this;
        }
    });
});